package com.pvj.myaccount.ui.slideshow

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.pvj.myaccount.AddActivity
import com.pvj.myaccount.KeyConfig
import com.pvj.myaccount.R
import com.pvj.myaccount.adapter.MonthCostAdapter
import com.pvj.myaccount.adapter.MonthCostRecyclerViewAdapter
import com.pvj.myaccount.adapter.RecyclerViewAdapter
import com.pvj.myaccount.databinding.FragmentSlideshowBinding
import com.pvj.myaccount.room.entity.Cost
import com.pvj.myaccount.room.entity.MonthCost
import com.pvj.myaccount.ui.home.RecycleViewDivider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SlideshowFragment : Fragment(), MonthCostRecyclerViewAdapter.OnItemClickListener {
    private val TAG = "SlideshowFragment"

    private var _binding: FragmentSlideshowBinding? = null
    private lateinit var recyclerViewAdapter: MonthCostRecyclerViewAdapter
    private lateinit var slideshowViewModel: MonthCostViewModel

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        slideshowViewModel =
            ViewModelProvider(this)[MonthCostViewModel::class.java]

        _binding = FragmentSlideshowBinding.inflate(inflater, container, false)
        val root: View = binding.root

        this.context?.let { recyclerViewAdapter = MonthCostRecyclerViewAdapter() }
        recyclerViewAdapter.setOnItemClickListener(this)
        _binding!!.recyclerView.layoutManager = LinearLayoutManager(activity) // 用于线性布局
        _binding!!.recyclerView.adapter = recyclerViewAdapter
        //添加自定义分割线：可自定义分割线高度和颜色
        _binding!!.recyclerView.addItemDecoration(
            RecycleViewDivider(
                activity,
                LinearLayoutManager.HORIZONTAL,
                20,
                resources.getColor(R.color.app_bg)
            )
        )

        slideshowViewModel.listMonthCost.observe(viewLifecycleOwner) {
            // 更新UI
            updateUI(it)
        }

        _binding!!.addBtn.setOnClickListener {
            startAddActivity(KeyConfig.TYPE_MONTH_COST)
        }

        return root
    }

    private fun startAddActivity(type: Int) {
        val intent = Intent(
            activity,
            AddActivity::class.java
        )
        intent.putExtra(KeyConfig.KEY_TYPE, type)
        // 启动目标Activity
        startActivity(intent)
    }

    private fun startAddActivity(type: Int,data: MonthCost) {
        val intent = Intent(activity, AddActivity::class.java)
        intent.putExtra(KeyConfig.KEY_TYPE, type)
        intent.putExtra(KeyConfig.KEY_DATA, data)
        startActivity(intent)
    }

    private fun updateUI(data: List<MonthCost>?) {
        // 更新列表、文本视图或其他UI组件
        recyclerViewAdapter!!.submitList(data)

        binding.textSlideshow.visibility = if (data.isNullOrEmpty()) View.VISIBLE else View.GONE
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume...")
        slideshowViewModel.loadDataAsync()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onUpdate(data: MonthCost) {
        startAddActivity(KeyConfig.TYPE_MONTH_COST,data)
    }

    override fun onDelete(data: MonthCost) {
        scope.launch {
            withContext(Dispatchers.IO) {
                slideshowViewModel.delete(data)
            }
            // 在这里更新UI线程
            withContext(Dispatchers.Main) {
                slideshowViewModel.loadDataAsync()
            }
        }
    }
}